import { Checkbox, Image, InputNumber, Button, Switch, message } from 'antd';
import { useEffect, useState } from 'react';
import './cart.css';
import {
    getCartItemList,
    updateCartItem,
    deleteCartItem
} from "../../../request/cart";
import { useNavigate } from "react-router-dom";

function Cart() {
    const navigate = useNavigate();
    const [cartItems, setCartItems] = useState([]);
    const [totalPrice, setTotalPrice] = useState(0);
    const [selectAll, setSelectAll] = useState(false);
    const [isAnyItemSelected, setIsAnyItemSelected] = useState(false); // 新增状态

    useEffect(() => {
        getCartItemList().then(cartList => {
            setCartItems(cartList);
        }).catch(({ msg }) => message.error(msg));
    }, []);

    const handleIncrement = (index) => {
        updateCartItem(cartItems[index].id, cartItems[index].number + 1)
            .then(() => {
                let updatedCartItems = [...cartItems];
                if (updatedCartItems[index].selected) {
                    let newTotalPrice = totalPrice + cartItems[index].option[0].price;
                    setTotalPrice(newTotalPrice);
                }
                updatedCartItems[index].number = updatedCartItems[index].number + 1;
                setCartItems(updatedCartItems);
            })
            .catch(({ msg }) => message.error(msg));
    };

    const handleDecrement = (index) => {
        updateCartItem(cartItems[index].id, cartItems[index].number - 1)
            .then(() => {
                let updatedCartItems = [...cartItems];
                if (updatedCartItems[index].selected) {
                    let newTotalPrice = totalPrice - cartItems[index].option[0].price;
                    setTotalPrice(newTotalPrice);
                }
                updatedCartItems[index].number = updatedCartItems[index].number - 1;
                setCartItems(updatedCartItems);
            })
            .catch(({ msg }) => message.error(msg));
    };

    const onChangeNumber = (index, value) => {
        if (value !== null) {
            updateCartItem(cartItems[index].id, value)
                .then(() => {
                    let updatedCartItems = [...cartItems];
                    if (updatedCartItems[index].selected) {
                        let newTotalPrice = totalPrice + cartItems[index].option[0].price * (value - cartItems[index].number);
                        setTotalPrice(newTotalPrice);
                    }
                    updatedCartItems[index].number = value;
                    setCartItems(updatedCartItems);
                })
                .catch(({ msg }) => message.error(msg));
        }
    };

    const handleDelete = (index) => {
        deleteCartItem(cartItems[index].id)
            .then(() => {
                if (cartItems[index].selected === true) {
                    let newTotalPrice = totalPrice - cartItems[index].option[0].price;
                    setTotalPrice(newTotalPrice);
                }
                const updatedCartItems = cartItems.filter((item, itemIndex) => itemIndex !== index);
                setCartItems(updatedCartItems);
            })
            .catch(({ msg }) => message.error(msg));
    };

    const handleSelected = (index) => {
        let updatedCartItems = [...cartItems];
        if (!updatedCartItems[index].selected) {
            setTotalPrice(totalPrice + cartItems[index].option[0].price * cartItems[index].number);
        } else {
            setTotalPrice(totalPrice - cartItems[index].option[0].price * cartItems[index].number);
        }
        updatedCartItems[index].selected = !updatedCartItems[index].selected;
        setCartItems(updatedCartItems);
    };

    const handleSelectedAll = () => {
        let updatedCartItems = [...cartItems];
        let newTotalPrice = 0;

        updatedCartItems = updatedCartItems.map((item) => {
            item.selected = !selectAll;
            if (!selectAll) {
                newTotalPrice += item.option[0].price * item.number;
            }
            return item;
        });

        setCartItems(updatedCartItems);
        setTotalPrice(newTotalPrice);
        setSelectAll(!selectAll);
    };

    const createOrder = () => {
        const selectedItems = cartItems.filter(item => item.selected).map(item => ({
            itemId: item.item.id,
            optionKey: item.option[0].key,
            img: item.option[0].img,
            label: item.item.label,
            optionName: item.option[0].name,
            optionPrice: item.option[0].price,
            number: item.number
        }));
        navigate('/purchase/create-order', { state: { items: selectedItems } });
    };

    useEffect(() => {
        setIsAnyItemSelected(cartItems.some(item => item.selected));
    }, [cartItems]);

    return (
        <div className="goods_list_container">
            {cartItems.map((item, index) => (
                <div className="goods" key={item.id}>
                    <div className="img_container">
                        <Checkbox className="select"
                            onChange={() => handleSelected(index)}
                            checked={item.selected}></Checkbox>
                        <div className="img">
                            <Image width={100} height={100} src={item.option[0].img} />
                        </div>
                    </div>
                    <div className="discribe_container">
                        <p className="title" onClick={() => {
                            navigate(`/item/${item.item.id}`);
                        }}>{item.item.label}</p>
                        <p className="discribe">{item.option[0].name}</p>
                        <p className="title">{"$" + item.option[0].price}</p>
                        <InputNumber
                            addonAfter={
                                <Button type="text" className="btn" onClick={() => handleIncrement(index)}>+</Button>
                            }
                            onChange={(value) => onChangeNumber(index, value)}
                            controls={false}
                            addonBefore={
                                <Button type="text" className="btn" onClick={() => handleDecrement(index)}>-</Button>
                            }
                            min={0}
                            className="input_number"
                            value={item.number}
                            defaultValue={1}
                        />
                    </div>
                    <div className="btn_container">
                        <Button type="text" onClick={() => handleDelete(index)}>
                            x
                        </Button>
                    </div>
                </div>
            ))}
            <div className="price_container">
                <Switch checkedChildren="清空" unCheckedChildren="全选" onChange={handleSelectedAll} />
                <p className="total_price">{"$" + totalPrice + "元"}</p>
                <Button type="primary" onClick={createOrder} disabled={!isAnyItemSelected}>去结算</Button>
            </div>
        </div>
    );
}

export default Cart;
